﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing.Drawing2D;
using System.Configuration;

namespace ImageResizeForAndroid
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window {
        BitmapImage sourceImageFile = null;
        string sourceFileName = "";
        string sourceFileNameWithoutExt = "";
        string destFolderName = "";
        int selectIconsItem = 0;
        bool saveFlag = false;
        bool isOverwrite = false;
        string ninetySixPx = "96 x 96 px";
        string seventyTwoPx = "72 x 72 px";
        string sixtyFourPx = "64 x 64 px";
        string fortyEightPx = "48 x 48 px";
        string thirtySixPx = "36 x 36 px";
        string thirtyTwoPx = "32 x 32 px";
        string twentyFourPx = "24 x 24 px";
        string eighteenPx = "18 x 18 px";
        string[] targetDensity = new string[] { "drawable-xhdpi", "drawable-hdpi", "drawable-mdpi", "drawable-ldpi" };
        int[] launchMenuSize = new int[]{ 96, 72, 48, 36 };
        int[] actionStatusSize = new int[] { 48, 36, 24, 18 };
        int[] tabDiagListSize = new int[] { 64, 48, 32, 24 };

        // MessageBox用変数
        MessageBoxButton button;
        MessageBoxImage icon;
        string messageBoxText;
        string caption;

        Window owner;

        public MainWindow() {
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.Manual;
            owner = this;
            InitMainWindow();
            System.Configuration.Configuration config =
                System.Configuration.ConfigurationManager.OpenExeConfiguration(
                    System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal);
            Console.WriteLine(config.FilePath);
        }

        // 新規作成処理
        private void InitMainWindow() {
            sourceImageFile = null;
            sourceFileName = "";
            sourceFileNameWithoutExt = "";
            selectIconsItem = 0;
            saveFlag = false;
            isOverwrite = false;
            sourceFile.Text = "";
            imageFileNameDisplay.Text = "";
            chooseImage.SetValue(System.Windows.Controls.Image.SourceProperty, null);
            destFolderName = Properties.Settings.Default.outputFolder;
            Console.WriteLine("Default output folder : " + destFolderName);
            destinationFolder.Text = destFolderName;
            launchMenuSelect.IsChecked = false;
            actionStatusSelect.IsChecked = false;
            tabDiagListSelect.IsChecked = false;
        }

        // 画像選択ボタン
        private void fileChoose_Click(object sender, RoutedEventArgs e) {
            string sourceFilePath = OpenDocument();
            if (sourceFilePath != "") {
                sourceFile.Text = sourceFilePath;
                try {
                    Uri imageuri = new Uri(sourceFilePath, UriKind.Absolute);
                    sourceImageFile = new BitmapImage(imageuri);
                    chooseImage.SetValue(System.Windows.Controls.Image.SourceProperty, sourceImageFile);
                } catch (NotSupportedException notsupportedexc) {
                    Console.WriteLine(notsupportedexc.ToString());
                }
            }
        }

        // 画像選択ボタンが押されたらファイル選択画面
        private String OpenDocument() {
            string filePath = "";
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.FileName = "";
            dlg.DefaultExt = ".png;.jpg;.jpeg;.gif;.bmp";
            dlg.Filter = "Image File|*.png;*.jpg;*.jpeg;*.gif;*.bmp|All Files(*.*)|*.*";
            dlg.ShowDialog();

            filePath = dlg.FileName;

            // ソースファイル名を取り出す
            sourceFileName = System.IO.Path.GetFileName(filePath);
            imageFileNameDisplay.Text = sourceFileName;

            return filePath;
        }

        // 選択画像のテキストボックスが変更されたら処理をする
        private void sourceFile_TextChanged(object sender, TextChangedEventArgs e) {
            string sourceFilePath = sourceFile.Text;
            if (sourceFilePath != "") {
                try {
                    Uri imageuri = new Uri(sourceFilePath, UriKind.Absolute);
                    
                    sourceImageFile = new BitmapImage(imageuri);
                    chooseImage.SetValue(System.Windows.Controls.Image.SourceProperty, sourceImageFile);
                } catch (UriFormatException uriformexception) {
                    Console.WriteLine("URiFormatException orrured:" + uriformexception.ToString());
                } catch (NotSupportedException noSupportedexception) {
                    messageBoxText = "Chosen file type invalid.\nPlease choose image file(.bmp/.gif/.jpg/.png).";
                    caption = "Error";
                    button = MessageBoxButton.OK;
                    icon = MessageBoxImage.Error;
                    System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
                    sourceFileName = "";
                    sourceFileNameWithoutExt = "";
                    sourceFile.Text = "";
                    imageFileNameDisplay.Text = "";
                    Console.WriteLine("NotSupportedException orrured:" + noSupportedexception.ToString());
                }
            }
        }

        // イメージ画像がfailedだったら
        private void chooseImage_ImageFailed(object sender, ExceptionRoutedEventArgs e) {}

        // 選択画像のテキストボックスのドラッグオーバーの処理
        private void sourceFile_PreviewDragOver(object sender, System.Windows.DragEventArgs e) {
            inputPreviewDragOver(sender, e);
        }

        // 選択画像のテキストボックスのドロップ処理
        private void sourceFile_Drop(object sender, System.Windows.DragEventArgs e) {
            inputDrop(sender, e);
        }

        // ファイル名のテキストブロッグのドラッグオーバー処理
        private void imageFileNameDisplay_PreviewDragOver(object sender, System.Windows.DragEventArgs e) {
            inputPreviewDragOver(sender, e);
        }

        // ファイル名のテキストブロッグにドロップされた時の処理
        private void imageFileNameDisplay_Drop(object sender, System.Windows.DragEventArgs e) {
            inputDrop(sender, e);
        }
        
        // 画像領域にドラッグオーバーされた時の処理
        private void ImageAreaBorder_PreviewDragOver(object sender, System.Windows.DragEventArgs e) {
            inputPreviewDragOver(sender, e);
        }

        // 画像領域にドロップされた時の処理
        private void ImageAreaBorder_Drop(object sender, System.Windows.DragEventArgs e) {
            inputDrop(sender, e);
        }

        // 画像にドラッグオーバーされた時の処理
        private void chooseImage_PreviewDragOver(object sender, System.Windows.DragEventArgs e) {
            inputPreviewDragOver(sender, e);
        }

        // 画像にドロップされた時の処理
        private void chooseImage_Drop(object sender, System.Windows.DragEventArgs e) {
            inputDrop(sender, e);
        }

        // ドラッグオーバーされた時の処理
        private void inputPreviewDragOver(object sender, System.Windows.DragEventArgs e) {
            if (e.Data.GetData(System.Windows.DataFormats.FileDrop) != null) {
                e.Effects = System.Windows.DragDropEffects.Copy;
            } else {
                e.Effects = System.Windows.DragDropEffects.None;
            }
            e.Handled = true;
        }

        // ドロップされた時の処理
        private void inputDrop(object sender, System.Windows.DragEventArgs e) {
            string[] files = e.Data.GetData(System.Windows.DataFormats.FileDrop) as string[];
            if (files != null) {
                //最初のファイルのPathを表示
                sourceFileName = System.IO.Path.GetFileName(files[0]);
                sourceFileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(files[0]);
                imageFileNameDisplay.Text = sourceFileName;
                sourceFile.Text = files[0];
                Console.WriteLine("Drop process");
            }
        }

        // 保存先選択ボタンが押されたら処理をする
        private void destChoose_Click(object sender, RoutedEventArgs e) {
            destinationFolder.Text = OpenDestFolder();
        }

        // フォルダ選択画面を表示
        private String OpenDestFolder() {
            FolderBrowserDialog fdlg = new FolderBrowserDialog();
            fdlg.Description = "Choose destination folder";

            DialogResult dr = fdlg.ShowDialog();

            if (dr == System.Windows.Forms.DialogResult.OK) {
                destFolderName = fdlg.SelectedPath;
            }
            return destFolderName;
        }

        // 出力先フォルダのドラッグオーバー処理
        private void destinationFolder_PreviewDragOver(object sender, System.Windows.DragEventArgs e) {
            if (e.Data.GetData(System.Windows.DataFormats.FileDrop) != null) {
                e.Effects = System.Windows.DragDropEffects.Copy;
            } else {
                e.Effects = System.Windows.DragDropEffects.None;
            }
            e.Handled = true;
        }

        // 出力先フォルダのドロップ処理
        private void destinationFolder_Drop(object sender, System.Windows.DragEventArgs e) {
            string[] files = e.Data.GetData(System.Windows.DataFormats.FileDrop) as string[];
            if (files != null) {
                //最初のファイルのPathを表示
                if (destinationFolderExist(files[0])) {
                    destFolderName = files[0];
                }
            }
        }

        private bool destinationFolderExist(string destinationPath) {
            if (Directory.Exists(destinationPath)) {
                destinationFolder.Text = destinationPath;
                return true;
            } else {
                messageBoxText = "Choose folder not exist or valid.\nPlease choose destination folder, again.";
                caption = "Error";
                button = MessageBoxButton.OK;
                icon = MessageBoxImage.Warning;
                System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
                return false;
            }
        }

        private void destinationFolder_TextChanged(object sender, TextChangedEventArgs e) {}

        // 実行ボタンが押された時の処理
        private void exeButton_Click(object sender, RoutedEventArgs e) {
            string destPath = destinationFolder.Text;
            if (sourceImageFile == null) {
                messageBoxText = "Please choose the Input Image File.";
                caption = "Error";
                button = MessageBoxButton.OK;
                icon = MessageBoxImage.Warning;
                System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
                return;
            } else if(destPath == "") {
                messageBoxText = "Please choose the Output folder.";
                caption = "Error";
                button = MessageBoxButton.OK;
                icon = MessageBoxImage.Warning;
                System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon); 
                return;
            } else {
                switch (selectIconsItem) {
                    case 1:
                        imageResize(launchMenuSize, destPath);
                        break;
                    case 2:
                        imageResize(launchMenuSize, destPath);
                        break;
                    case 3:
                        imageResize(launchMenuSize, destPath);
                        break;
                    default:
                        messageBoxText = "Please choose the icon set.";
                        caption = "Error";
                        button = MessageBoxButton.OK;
                        icon = MessageBoxImage.Warning;
                        System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
                        return;
                }
                if (saveFlag) {
                    SavedWindow savedwindow = new SavedWindow(destFolderName);
                    savedwindow.Owner = System.Windows.Application.Current.MainWindow;
                    savedwindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
                    savedwindow.ShowDialog();
                    saveFlag = false;
                    return;
                } else {
                    Window owner = this;
                    messageBoxText = "File was not saved!";
                    caption = "Error";
                    button = MessageBoxButton.OK;
                    icon = MessageBoxImage.Warning;
                    System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
                }
            }
    
        }
        
        // 画像のリサイズを行う
        private void imageResize(int[] targetSize, string destPath) {
            Bitmap src = new Bitmap(sourceFile.Text);
            string targetPath;
            for (int i = 0; i < targetSize.Length; i++) {
                // ターゲットのディレクトリを作成
                Directory.CreateDirectory(destPath + "\\" + targetDensity[i]);
                targetPath = destPath + "\\" + targetDensity[i] + "\\" + sourceFileNameWithoutExt + ".png";

                if(!isOverwrite) {
                    if (File.Exists(targetPath)) {
                        messageBoxText = "A file of the same name already exists, Overwrite?";
                        caption = "Warning";
                        button = MessageBoxButton.YesNo;
                        icon = MessageBoxImage.Warning;
                        MessageBoxResult mbr = System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
                        if (mbr != MessageBoxResult.Yes) {
                            return;
                        }
                        isOverwrite = true;
                    }
                }
                Bitmap dest = new Bitmap(targetSize[i], targetSize[i]);
                Graphics g = Graphics.FromImage(dest);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(src, 0, 0, targetSize[i], targetSize[i]);
                try {
                    dest.Save(targetPath, ImageFormat.Png);
                    saveFlag = true;
                } catch (ExternalException e) { }
            }
            isOverwrite = false;
        }

        // ランチャーとメニュー用のアイコンセットを選択
        private void launchMenuSelect_Checked(object sender, RoutedEventArgs e) {
            selectIconsItem = 1;
            xhdpiText.Text = ninetySixPx;
            hdpiText.Text = seventyTwoPx;
            mdpiText.Text = fortyEightPx;
            ldpiText.Text = thirtySixPx;
        }

        // アクションバーとステータスバー用のアイコンセットを選択
        private void actionStatusSelect_Checked(object sender, RoutedEventArgs e) {
            selectIconsItem = 2;
            xhdpiText.Text = fortyEightPx;
            hdpiText.Text = thirtySixPx;
            mdpiText.Text = twentyFourPx;
            ldpiText.Text = eighteenPx;
        }

        // タグとダイアログとリストビュー用のアイコンセットを選択
        private void tabDiagListSelect_Checked(object sender, RoutedEventArgs e) {
            selectIconsItem = 3;
            xhdpiText.Text = sixtyFourPx;
            hdpiText.Text = fortyEightPx;
            mdpiText.Text = thirtyTwoPx;
            ldpiText.Text = twentyFourPx;
        }

        // メニューのNewが押された時の処理
        private void menuNew_Click(object sender, RoutedEventArgs e) {
            InitMainWindow();
        }

        // メニューのExitが押された時の処理
        private void menuExit_Click(object sender, RoutedEventArgs e) {
            this.Close();
        }

        // メニューのSettingsが押された時の処理
        private void menuSetting_Click(object sender, RoutedEventArgs e) {
            SettingsWindow sw = new SettingsWindow();
            sw.Owner = System.Windows.Application.Current.MainWindow;
            sw.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            sw.ShowDialog();
            destFolderName = Properties.Settings.Default.outputFolder;
            destinationFolder.Text = destFolderName;
        }

        // メニューのAboutが押された時の処理
        private void menuAbout_Click(object sender, RoutedEventArgs e) {
            aboutWindow aboutdlg = new aboutWindow();
            aboutdlg.Owner = System.Windows.Application.Current.MainWindow;
            aboutdlg.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            aboutdlg.ShowDialog();
        }

        // 保存先フォルダパスを取得する
        public string getDestinationFolder() {
            return destinationFolder.Text;
        }
    }
}
